<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="订单编号" prop="purchasePlanNo">
          <el-input v-model="queryParams.purchasePlanNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-select v-model="queryParams.customerName" placeholder="请选择客户" clearable filterable>
            <el-option v-for="dict in customerOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="交货日期">
          <el-date-picker v-model="daterangeDeliveryDate" style="width: 240px" value-format="YYYY-MM-DD" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="签订日期">
          <el-date-picker v-model="daterangeSignDate" style="width: 240px" value-format="YYYY-MM-DD" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="申请人" prop="applyUser">
          <el-select v-model="queryParams.applyUser" placeholder="请选择申请人" clearable filterable>
            <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请日期">
          <el-date-picker v-model="daterangeApplyTime" style="width: 240px" value-format="YYYY-MM-DD" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <el-select v-model="queryParams.applyStatus" placeholder="请选择申请状态：" clearable filterable>
            <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" prop="auditUser">
          <el-select v-model="queryParams.auditUser" placeholder="请选择审核人" clearable filterable>
            <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核日期">
          <el-date-picker v-model="daterangeAuditTime" style="width: 240px" value-format="YYYY-MM-DD" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态：" clearable filterable>
            <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
      </el-row>
  
      <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="合同编号" align="center" prop="contractNo" />
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="业务员" align="center" prop="workStaff" :formatter="workStaffFormat" />
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="交货日期" align="center" prop="deliveryDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="送货方式" align="center" prop="deliveryType" :formatter="deliveryTypeFormat" />
        <el-table-column label="合同金额" align="center" prop="contractAmount" />
        <el-table-column label="签订日期" align="center" prop="signDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.signDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请人" align="center" prop="applyUser" :formatter="applyUserFormat" />
        <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请状态" align="center" prop="applyStatus" :formatter="applyStatusFormat" />
        <el-table-column label="审核人" align="center" prop="auditUser" :formatter="auditUserFormat" />
        <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="auditStatusFormat" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
  
      <!-- 添加或修改采购计划对话框 -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="90px" :inline="true">
          <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="form.orderNo" placeholder="请输入订单编号" disabled />
          </el-form-item>
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="form.customerName" disabled />
          </el-form-item>
          <el-form-item label="交货日期" prop="deliveryDate">
            <el-date-picker v-model="form.deliveryDate" type="date" value-format="YYYY-MM-DD" placeholder="选择交货日期" disabled />
          </el-form-item>
          <el-form-item label="申请人" prop="applyUser">
            <el-select v-model="form.applyUser" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请日期" prop="applyTime">
            <el-date-picker v-model="form.applyTime" type="date" value-format="YYYY-MM-DD" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="申请状态" prop="applyStatus">
            <el-select v-model="form.applyStatus" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核人" prop="auditUser">
            <el-select v-model="form.auditUser" placeholder="请选择审核人" clearable filterable disabled>
              <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核日期" prop="auditTime">
            <el-date-picker v-model="form.auditTime" type="date" value-format="YYYY-MM-DD" placeholder="选择审核日期" disabled />
          </el-form-item>
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="form.auditStatus" placeholder="请选择审核状态：" clearable filterable disabled>
              <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="审核意见" prop="auditComment">
            <el-input v-model="form.auditComment" type="textarea" placeholder="请输入审核意见" />
          </el-form-item>
          <el-divider content-position="center">销售订单详细信息</el-divider>
          <el-table :data="scmSaleContractDetailList" :row-class-name="rowScmSaleContractDetailIndex" ref="detailTableRef">
            <el-table-column label="序号" align="center" prop="index" width="50" />
            <el-table-column label="产品" prop="materialName" width="300" />
            <el-table-column label="型号" prop="materialModel" />
            <el-table-column label="规格" prop="materialSpecification" />
            <el-table-column label="单位" prop="materialUnit" />
            <el-table-column label="单价" prop="price" width="150" />
            <el-table-column label="订货数量" prop="quantity" width="150" />
            <el-table-column label="金额" prop="amount" width="150" />
            <el-table-column label="备注" prop="detailRemark" width="150" />
          </el-table>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button v-if="form.applyStatus!='2'" type="primary" @click="submitForm('1')">通 过</el-button>
            <el-button v-if="form.applyStatus!='2'" type="warning" @click="submitForm('0')">驳 回</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Search, Refresh, Edit } from '@element-plus/icons-vue'
  import { parseTime } from '@/utils/ruoyi'
  import { getDicts } from '@/api/system/dict/data'
  import { selectDictLabel } from '@/utils/ruoyi'
  import useUserStore from '@/store/modules/user'
  import {
    listContract4Audit,
    getContract,
    auditContract
  } from "@/api/sale/contract"
  
  // refs
  const queryFormRef = ref()
  const formRef = ref()
  const detailTableRef = ref()
  
  // 状态数据
  const loading = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSearch = ref(true)
  const total = ref(0)
  const open = ref(false)
  const title = ref('')
  
  // 选项数据
  const workStaffOptions = ref([])
  const applyUserOptions = ref([])
  const applyStatusOptions = ref([])
  const customerOptions = ref([])
  const auditUserOptions = ref([])
  const auditStatusOptions = ref([])
  const deliveryTypeOptions = ref([])
  
  // 列表数据
  const contractList = ref([])
  const scmSaleContractDetailList = ref([])
  
  // 日期范围
  const daterangeDeliveryDate = ref([])
  const daterangeSignDate = ref([])
  const daterangeApplyTime = ref([])
  const daterangeAuditTime = ref([])
  
  // stores
  const userStore = useUserStore()
  
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    contractNo: null,
    orderId: null,
    orderNo: null,
    workStaff: null,
    customerName: null,
    deliveryDate: null,
    deliveryType: null,
    signDate: null,
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
  })
  
  // 表单数据
  const form = reactive({
    id: null,
    contractNo: null,
    orderNo: null,
    workStaff: null,
    customerName: null,
    deliveryDate: null,
    deliveryType: null,
    signDate: null,
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
    remark: null,
    auditComment: null,
    scmSaleContractDetailList: []
  })
  
  // 表单验证
  const checkAuditComment = (rule, value, callback) => {
    if (form.auditStatus === '0' && !value) {
      callback(new Error('请输入审核意见'))
      return
    }
    callback()
  }
  
  const rules = {
    auditComment: [{ validator: checkAuditComment, trigger: 'blur' }]
  }
  
  // 监听明细列表变化
  watch(scmSaleContractDetailList, (newVal) => {
    form.scmSaleContractDetailList = newVal
  }, { deep: true, immediate: true })
  
  // 方法
  const getList = async () => {
    loading.value = true
    try {
      const params = {
        ...queryParams,
        params: {}
      }
      if (daterangeDeliveryDate.value?.length) {
        params.params.beginDeliveryDate = daterangeDeliveryDate.value[0]
        params.params.endDeliveryDate = daterangeDeliveryDate.value[1]
      }
      if (daterangeSignDate.value?.length) {
        params.params.beginSignDate = daterangeSignDate.value[0]
        params.params.endSignDate = daterangeSignDate.value[1]
      }
      if (daterangeApplyTime.value?.length) {
        params.params.beginApplyTime = daterangeApplyTime.value[0]
        params.params.endApplyTime = daterangeApplyTime.value[1]
      }
      if (daterangeAuditTime.value?.length) {
        params.params.beginAuditTime = daterangeAuditTime.value[0]
        params.params.endAuditTime = daterangeAuditTime.value[1]
      }
      const response = await listContract4Audit(params)
      contractList.value = response.rows
      total.value = response.total
    } finally {
      loading.value = false
    }
  }
  
  // 格式化方法
  const deliveryTypeFormat = (row) => selectDictLabel(deliveryTypeOptions.value, row.deliveryType)
  const workStaffFormat = (row) => selectDictLabel(workStaffOptions.value, row.workStaff)
  const applyUserFormat = (row) => selectDictLabel(applyUserOptions.value, row.applyUser)
  const applyStatusFormat = (row) => selectDictLabel(applyStatusOptions.value, row.applyStatus)
  const auditUserFormat = (row) => selectDictLabel(auditUserOptions.value, row.auditUser)
  const auditStatusFormat = (row) => selectDictLabel(auditStatusOptions.value, row.auditStatus)
  
  // 操作方法
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }
  
  const resetQuery = () => {
    daterangeDeliveryDate.value = []
    daterangeSignDate.value = []
    daterangeApplyTime.value = []
    daterangeAuditTime.value = []
    queryFormRef.value?.resetFields()
    handleQuery()
  }
  
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    multiple.value = !selection.length
  }
  
  const handleUpdate = async (row) => {
    const id = row.id || ids.value
    try {
      const response = await getContract(id)
      Object.assign(form, response.data)
      scmSaleContractDetailList.value = response.data.scmSaleContractDetailList
      open.value = true
      title.value = "审核销售合同"
    } catch (error) {
      console.error('获取合同详情失败:', error)
    }
  }
  
  const submitForm = async (status) => {
    form.auditStatus = status
    try {
      await formRef.value?.validate()
      // 设置审核人为当前用户
      form.auditUser = userStore.id
      // 设置审核时间为当前时间
      form.auditTime = parseTime(new Date(), '{y}-{m}-{d}')
      await auditContract(form)
      ElMessage.success("审核成功")
      open.value = false
      getList()
    } catch (error) {
      console.error('审核失败:', error)
    }
  }
  
  const cancel = () => {
    open.value = false
  }
  
  const rowScmSaleContractDetailIndex = ({ row, rowIndex }) => {
    row.index = rowIndex + 1
  }
  
  // 初始化
  onMounted(async () => {
    try {
      const [
        workStaffRes,
        applyStatusRes,
        customerRes,
        auditStatusRes,
        deliveryTypeRes
      ] = await Promise.all([
        getDicts("sys_user"),
        getDicts("apply_status"),
        getDicts("query_customer"),
        getDicts("audit_status"),
        getDicts("scm_delivery_type")
      ])
  
      workStaffOptions.value = workStaffRes.data
      applyUserOptions.value = workStaffRes.data
      auditUserOptions.value = workStaffRes.data
      applyStatusOptions.value = applyStatusRes.data
      customerOptions.value = customerRes.data
      auditStatusOptions.value = auditStatusRes.data
      deliveryTypeOptions.value = deliveryTypeRes.data
  
      await getList()
    } catch (error) {
      console.error('初始化失败:', error)
    }
  })
  </script> 